<!-- 树状选择器 -->
<template>
  <el-popover
    ref="popover"
    placement="bottom-start"
    trigger="focus"
    class="select-tree-popover"
    @show="onShowPopover"
    @hide="onHidePopover"
  >
    <el-tree
      ref="tree"
      class="select-tree"
      highlight-current
      :style="`min-width: ${treeWidth}`"
      :data="data"
      :props="props"
      node-key="id"
      empty-text="没有相关的选项！"
      :default-expanded-keys="defaultExpandedKeys"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :default-expand-all="defaultExpandAll"
      :render-content="renderContent"
      @node-click="onClickNode"
    />

    <el-input
      slot="reference"
      ref="input"
      v-model="labelModel"
      :style="`width: ${width}px`"
      :class="{ 'rotate': showStatus }"
      suffix-icon="el-icon-arrow-down"
      :placeholder="placeholder"
      :readonly="readonly"
    >
      <el-button v-if="clearable" slot="append" icon="el-icon-circle-close" @click="onClear($event)" />
    </el-input>
  </el-popover>
</template>

<script>
export default {
  name: 'SelectTree',
  // 设置绑定参数
  model: {
    prop: 'value',
    event: 'selected'
  },
  props: {
    // 接收绑定参数
    value: {
      type: [String, Number],
      required: false,
      default: ''
    },
    // 输入框宽度
    // eslint-disable-next-line vue/require-default-prop
    width: {
      type: String,
      required: false
    },
    // 选项数据
    options: {
      type: Array,
      required: true
    },
    defaultExpandedKeys: { // 要设置 node-key="id"
      type: Array,
      default: () => { return [] }
    },
    readonly: {
      type: Boolean,
      default: true
    },
    defaultExpandAll: {
      type: Boolean,
      default: false
    },
    /* 只能选择叶子节点 */
    onlyLeaf: {
      type: Boolean,
      default: false
    },
    /* 可清空选项,input 是readonly时clearable 没用，此时使用button代替 */
    clearable: {
      type: Boolean,
      default: () => { return false }
    },
    // 输入框占位符
    placeholder: {
      type: String,
      required: false,
      default: '请选择'
    },
    // 树节点配置选项
    props: {
      type: Object,
      required: false,
      default: () => ({
        parent: 'parentId',
        value: 'id',
        label: 'label',
        children: 'children'
      })
    }
  },
  data() {
    return {
      // 树状菜单显示状态
      showStatus: false,
      // 菜单宽度
      treeWidth: 'auto',
      // 输入框显示值
      labelModel: null,
      // 实际请求传值
      valueModel: null
    }
  },
  computed: {
    data() {
      return this.options
    }
  },
  watch: {
    labelModel(val) {
      if (!val) {
        this.valueModel = null
      }
      this.$refs.tree.filter(val)
    },
    value(val) {
      // console.log('treeid:' + val)
      this.labelModel = this.queryTree(this.data, val)
      if (this.labelModel !== '') { // finded
        this.valueModel = val
      } else {
        this.valueModel = null
      }
    }
  },
  created() {
    // 检测输入框原有值并显示对应 label
    //  console.log('tree.id:' + this.value)
    if (this.value === 0 || this.value) {
      this.labelModel = this.queryTree(this.data, this.value)
    }
    // 获取输入框宽度同步至树状菜单宽度
    this.$nextTick(() => {
      this.treeWidth = `${(this.width || this.$refs.input.$refs.input.clientWidth) - 24}px`
    })
  },
  methods: {
    renderContent(h, { node, data, store }) {
      if (node.data.disabled) {
        return (
          <span class='el-tree-node__label d-disabled-true'>
            {node.label}
          </span>
        )
      } else {
        return (
          <span class='el-tree-node__label'>
            {node.label}
          </span>
        )
      }
    },
    // 单击节点
    onClickNode(node) {
      if (node.disabled) {
        return
      }
      if (this.onlyLeaf) {
        if (node.children && node.children.length > 0) {
          return
        } else {
          this.labelModel = node[this.props.label]
          this.valueModel = node[this.props.value]
          this.onCloseTree()
        }
      } else {
        this.labelModel = node[this.props.label]
        this.valueModel = node[this.props.value]
        this.onCloseTree()
      }
    },
    // 隐藏树状菜单
    onCloseTree() {
      this.$refs.popover.showPopper = false
    },
    // 显示时触发
    onShowPopover() {
      this.showStatus = true
      this.$refs.tree.filter(false)
    },
    // 隐藏时触发，返回调用值this.valueModel，emit selected 设置控件值
    onHidePopover() {
      this.showStatus = false
      // 如果按输入没找到相关的值，显示原来的值此
      if (!this.readonly) {
        this.labelModel = this.queryTree(this.data, this.valueModel)
      }
      this.$emit('selected', this.valueModel)
    },
    onClear(event) {
      // event.preventDefault()
      event.stopPropagation()
      this.valueModel = null
      this.$emit('selected', this.valueModel)
    },
    // 树节点过滤方法
    filterNode(query, data) {
      if (!query) return true
      return data[this.props.label].indexOf(query) !== -1
    },
    // 搜索树状数据中的 ID
    queryTree(tree, id) {
      let stark = []
      stark = stark.concat(tree)
      while (stark.length) {
        const temp = stark.shift()
        if (temp[this.props.children]) {
          stark = stark.concat(temp[this.props.children])
        }
        if (temp[this.props.value] === id) {
          if (temp.disabled) {
            return ''
          }
          return temp[this.props.label]
        }
      }
      return ''
    },
    // 给父组件调用
    getTreeNode(id) {
      let stark = []
      stark = stark.concat(this.data)
      while (stark.length) {
        const temp = stark.shift()
        if (temp[this.props.children]) {
          stark = stark.concat(temp[this.props.children])
        }
        if (temp[this.props.value] === id) {
          return temp
        }
      }
      return null
    }

  }
}
</script>

<style>
  .select-tree-popover .el-input-group__append  {
    padding: 0px 8px;
    background-color:#ffffff ;
  }
  .select-tree {
    max-height: 250px;
    overflow-y: scroll;
  }
  /* 菜单滚动条 */
  .select-tree::-webkit-scrollbar {
    z-index: 11;
    width: 6px;
  }
  .select-tree::-webkit-scrollbar-track,
  .select-tree::-webkit-scrollbar-corner {
    background: #fff;
  }
  .select-tree::-webkit-scrollbar-thumb {
    border-radius: 5px;
    width: 6px;
    background: #b4bccc;
  }
  .select-tree::-webkit-scrollbar-track-piece {
    background: #fff;
    width: 6px;
  }
</style>
